package com.wn.portal.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.rmi.runtime.Log;

import java.util.List;

/**
 * @author yellow Docter
 * @date 2022 -08-23
 * @desc
 */
@RestController
@RequestMapping("discovery")
@Slf4j
public class PorTalServiceController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     *  服务发现
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("{mid}")
    public String findMemberById(@PathVariable Integer mid){

        log.info("请求过来。。。{}",mid);

        // 之前的写法
//        String url = "http://localhost:8080/member/" +mid;

        //通过服务发现 可以获取服务实例

        //通过微服的名称获取服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("MEMBER-SERVER");
        int size = instances.size();
        log.info("获取服务实例的个数:{}",size);
        // 获取服务的实例
        ServiceInstance serviceInstance = instances.get(0);

        //包含了 url一些信息
        String host = serviceInstance.getHost();  // 注解
        int port = serviceInstance.getPort();
        log.info("获取主机host:{}",host);
        log.info("获取主机port:{}",port);
        String url = "http://" + host + ":" + port + "/member/" + mid;

        String str = restTemplate.getForObject(url, String.class);

        return str;

    }

}
